//
//  AugmentedRealityCamera.m
//  POCRA
//
//  Created by Marcel Arbó Lack on 26/11/10.
//  Copyright 2010 Mobivery. All rights reserved.
//


#import "AugmentedRealityCamera.h"
#import <QuartzCore/QuartzCore.h>
#import "ARGeoCoordinate.h"

@interface AugmentedRealityCamera(Private)

// Visualiza la camara
- (void)openCamera;
// Configura la camara
- (void)configureCamera;

@end


@implementation AugmentedRealityCamera

@synthesize overlay;
@synthesize vectorView;
@synthesize locationManager;
@synthesize arrayOfInformation = arrayOfInformation_;

@synthesize providerDelegate = providerDelegate_;

@synthesize feetView = feetView_;

- (void)dealloc {
		
	[vectorView release]; vectorView = nil;
	[locationManager release]; locationManager = nil;
	[arrayOfInformation_ release]; arrayOfInformation_ = nil;
	[feetView_ release]; feetView_ = nil;
	
    [super dealloc];
	
}

- (void)viewDidLoad {
	
	// Guardamos la instancia del vector
	vectorView = [[ARVectorViewController alloc] initWithNibName:@"ARVectorView" bundle:nil];
	feetView_ = [[ARFeetViewController alloc] initWithNibName:@"ARFeetView" bundle:nil];
	[[feetView_ distanceLabel] setText:@""];
	
	// Inicializacion referente al location manager	
	locationManager = [[CLLocationManager alloc] init];
	self.locationManager.delegate = self;	
	[locationManager startUpdatingLocation];
	
	// Vista que se coloca sobre la camara
	overlay = [[OverlayViewController alloc] initWithImagePicker:self AndLocationMan:locationManager];
	[overlay setDelegate:self];	
	[overlay setAccelerometerDelegate:self];
	[overlay setLocationDelegate:self];
	[overlay startListening];
	[overlay setOverlayDelegate:self];
	
	[self configureCamera];
	[self openCamera];
		
}

- (void)viewDidUnload {
	
	self.cameraOverlayView = nil;
	
	[super viewDidUnload];
	
}

#pragma mark -
#pragma mark Metodos de ARViewDelegate

- (UIView *)viewForCoordinate:(ARCoordinate *)coordinate{
	
	// Le pedimos el controlador al delegado
	UIViewController * controller = [providerDelegate_ arControllerForARCoordinate:coordinate];
	
	// Se anyade a la Lista de controladores
	[overlay addTagController:controller];
	
	// Se devuelve la vista
	return [controller view];
	
}

- (void)loadNewPresetSelection:(NSInteger)selection {
	
}

#pragma mark -
#pragma mark UIAccelerometerDelegate protocol

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
	
	//NSLog(@"Aceleracion : %f, %f, %f", acceleration.x, acceleration.y, acceleration.z);
	
	// Determina si se esta apuntando al suelo con la camara
	BOOL result = [overlay changeInclination:YES];
	
	// Si se esta apuntando al suelo
	if (result == YES) {
		
		//NSLog(@"Inclinacion cambiada!");
		
		// Si hay un punto seleccionado
		if ([overlay IsOrientedActived]) {
			
			// Si no se encuentra el vector de direccion en pantalla
			if (!vectorView.view.superview) {
				
				// Se colocan los textos de la vista del vector y se actualizan
				[vectorView setNameVector:[overlay getVectorName]];
				[vectorView setUpdateDistance:[overlay getVectorDistance]];
				
				//NSLog(@"tagselected %d",overlay.tagSelected);
				
				// Se obtienen las coordenadas y se calcula el giro del vector
				ARGeoCoordinate *coord = (ARGeoCoordinate*)[overlay GetCoordinates:overlay.tagSelected - 1];
				
				// Si el giro es negativo
				if (coord.azimuth < 0.0) {
					
					// Se calcula el mismo angulo en positivo
					[vectorView setMyazimuth:(2*M_PI) - coord.azimuth];
				} else {
					
					[vectorView setMyazimuth:coord.azimuth];
				}
				
				// Y se establece la localizacion en la vista vector
				[vectorView setMylocation:coord.geoLocation];
				
				// La distancia ya no va en el vector, por lo que colocamos su label como vacio
				[vectorView setUpdateDistance:@""];
				
				// Se quita animadamente la vista seleccionada
				[overlay showHideDetailView:NO];
				
				// y se coloca el vector animadamente
				[overlay.view addSubview:vectorView.view];
				vectorView.view.frame = CGRectMake(70.0, 200.0, vectorView.view.frame.size.width, vectorView.view.frame.size.height);
				
				CATransition *animation = [CATransition animation];				
				[animation setType:kCATransitionFade];				
				[animation setDuration:0.75];
				[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];				
				[[overlay.view layer] addAnimation:animation forKey:@"transitionViewAnimation"];
				
				// Anyadir pie de RA				
				[[feetView_ view] setFrame:CGRectMake(0, 387, 320, 93)];
				[[feetView_ addressLabel] setText:coord.aditionalInfo];
				[overlay.view addSubview:feetView_.view];
				[overlay getRadarAndBackButtonToTheFront];
				
			} 
			else {
				//	Si el vector ya esta visible
				
				// Se obtienen las coordenadas para calcular las distancias
				ARGeoCoordinate *coord = (ARGeoCoordinate*)[overlay GetCoordinates:overlay.tagSelected - 1];				
				
				// Se gira
				if ([overlay GetLandscapeCondition] == NO) {
					
					vectorView.view.transform = CGAffineTransformMakeRotation((-overlay.centerCoordinate.azimuth + vectorView.myazimuth) - M_PI/2.0);
					
				} else {
					
					vectorView.view.transform = CGAffineTransformMakeRotation(-overlay.centerCoordinate.azimuth + vectorView.myazimuth);
					
				}	
				
				// Comentado porque la distancia ya no va en el vector
				//[vectorView setUpdateDistance:[overlay getVectorDistance]];
				
				//Actualizamos la distancia de la RA
				[[feetView_ distanceLabel] setText:[NSString stringWithFormat:@"%.0f m", [locationManager.location distanceFromLocation:coord.geoLocation]]];
				
			}		
		}
	} 
	else {	
		//	Si no esta apuntando al suelo con la camara
			
		// Si esta vector view en escena
		if (vectorView.view.superview) {
			
			// Se quita de la escena animadamente
			[vectorView.view removeFromSuperview];
			vectorView.view.transform = CGAffineTransformIdentity;
			
			[overlay showHideDetailView:YES];
			
			CATransition *animation = [CATransition animation];
			[animation setType:kCATransitionFade];
			[animation setDuration:0.75];
			[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
			
			// Se anyade la animacion
			[[overlay.view layer] addAnimation:animation forKey:@"transitionViewAnimation"];
			
			// TODO Eliminar pie de RA
			[[feetView_ view] removeFromSuperview];
		}
	}
}



#pragma mark -
#pragma mark CLLocationManagerDelegate protocol

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
	
	// Actualiza los puntos del radar cuando se registra una nueva posicion
	double myazimuth = fmod(newHeading.magneticHeading, 360.0) * (2 * (M_PI / 360.0));	
	[overlay changeRadarsPointsPosition:myazimuth];
	
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	NSLog(@"AugmentedRealityCamera - my new location: %f, %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
	[vectorView updateDistance:newLocation];
	
}

#pragma mark -
#pragma mark Metodos privados

// Para la localizacion
-(void)timeOut {
	
	NSLog(@"TimingOut Location");
	[locationManager stopUpdatingLocation];
	
}

// Configura la camara
- (void)configureCamera {
	
	// Hide Apple's UI
	self.sourceType = UIImagePickerControllerSourceTypeCamera;
	self.showsCameraControls = NO;
	self.navigationBarHidden = YES;
	self.toolbarHidden = YES;
	self.wantsFullScreenLayout = YES;
	
}

// Se encarga de visualizar la camara y mostrar la vista de RA por encima
- (void)openCamera {
	
	// Pasamos a la vista overlay los puntos de interes, y los cargamos todos
	[overlay loadDataModelAccessArray:arrayOfInformation_ maximumTags:[arrayOfInformation_ count]];
	
	// Se le dice a la camara que vista debe tener por delante
	self.cameraOverlayView = [overlay view];	
	self.cameraViewTransform = CGAffineTransformScale(self.cameraViewTransform, 1.25f, 1.25f);
	
}

#pragma mark -
#pragma mark Metodos de OverlayViewControllerDelegate

// Hace salir de la vista de RA
- (void)exitRAView {
	
	self.cameraOverlayView = nil;
	[overlay unloadView];
	[overlay release]; overlay = nil;
	[locationManager stopUpdatingLocation];
	
	[self dismissModalViewControllerAnimated:YES];	
	
}

- (ARDetailViewController *)detailForCoordinate:(ARCoordinate *)coordinate{

	return [providerDelegate_ arDetailControllerForARCoordinate:coordinate];
	
}

@end
